﻿using LibraryManagementSystem.Models;
using LibraryManagementSystem.Services.Interfaces;
using MySql.Data.MySqlClient;
using System;
using System.Threading.Tasks;

public class UserService : IUserService
{
    private readonly LibraryDbContext _dbContext;
    private readonly IPasswordHasher _passwordHasher;

    public UserService(LibraryDbContext dbContext, IPasswordHasher passwordHasher)
    {
        _dbContext = dbContext;
        _passwordHasher = passwordHasher;
    }

    public async Task<User> Authenticate(int username, string password)
    {
        using (var command = _dbContext.CreateCommand())
        {
            command.CommandText = "SELECT * FROM Users WHERE Username = @Username";
            command.Parameters.AddWithValue("@Username", username);

            using (var reader = await command.ExecuteReaderAsync())
            {
                // 打印出列信息
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    Console.WriteLine($"Column {i}: Name = {reader.GetName(i)}, Type = {reader.GetDataTypeName(i)}");
                }

                if (await reader.ReadAsync())
                {
                    var user = new User
                    {
                        Username = reader.GetInt32(reader.GetOrdinal("Username")), 
                        Password = reader.GetString(reader.GetOrdinal("Password")),
                        RealName = reader.GetString(reader.GetOrdinal("RealName")),
                        Email = reader.GetString(reader.GetOrdinal("Email")),
                        Phone = reader.GetString(reader.GetOrdinal("Phone")),
                        UserType = reader.GetString(reader.GetOrdinal("UserType")),
                        MaxBorrowLimit = reader.GetInt32(reader.GetOrdinal("MaxBorrowLimit"))
                    };

                    if (_passwordHasher.Verify(user.Password, password))
                    {
                        return user;
                    }
                }

                return null; // 如果没有找到用户或密码不匹配，返回 null
            }
        }
        return null;
    }

    public async Task<bool> Register(User user, string password)
    {
        if (!await IsUsernameAvailable(user.Username))
        {
            return false;
        }

        var hashedPassword = _passwordHasher.Hash(password);

        using (var command = _dbContext.CreateCommand())
        {
            command.CommandText = @"
                INSERT INTO Users (Username, Password, RealName, Email, Phone, UserType, MaxBorrowLimit)
                VALUES (@Username, @Password, @RealName, @Email, @Phone, @UserType, @MaxBorrowLimit)";

            command.Parameters.AddWithValue("@Username", user.Username);
            command.Parameters.AddWithValue("@Password", hashedPassword);
            command.Parameters.AddWithValue("@RealName", user.RealName);
            command.Parameters.AddWithValue("@Email", user.Email);
            command.Parameters.AddWithValue("@Phone", user.Phone);
            command.Parameters.AddWithValue("@UserType", user.UserType);
            command.Parameters.AddWithValue("@MaxBorrowLimit", user.MaxBorrowLimit);

            var rowsAffected = await command.ExecuteNonQueryAsync();
            return rowsAffected > 0;
        }
    }

    public async Task<bool> IsUsernameAvailable(int username)
    {
        using (var command = _dbContext.CreateCommand())
        {
            command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = @Username";
            command.Parameters.AddWithValue("@Username", username);

            var count = Convert.ToInt32(await command.ExecuteScalarAsync());
            return count == 0;
        }
    }
}